package hyy_2022;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class _0718_144_PreorderTraversal {

    public  List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        preorder(root, res);
        return res;
    }

    /**
     * 前序遍历
     * @param root
     * @param res
     */
    public void preorder(TreeNode root, List<Integer> res) {
        if(root == null) {
            return;
        }
        res.add(root.val);
        preorder(root.left,res);
        preorder(root.right,res);
    }

    public List<Integer> preorder(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null) {
            return null;
        }

        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode node = null;
        while(!stack.isEmpty() || node != null) {
            while(node != null) {
                res.add(node.val);
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            node = node.right;
        }
        return res;
    }
}
